# -*- coding:utf-8 -*-
from manager.models import *
from userprofile.models import *
from .ext import common as common_tools
from .ext.excelhelper import render_to_excel
# from .ext.shppis import *
from django.contrib.auth.models import User, Group
from django.contrib import auth
from django.db.models import Sum, Count, Q
from django.db import connection
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, render_to_response, HttpResponseRedirect, HttpResponse
import json, datetime, requests, time


@csrf_exempt
def in_parking_list(request):
    # origin_ip = request.META['REMOTE_ADDR']         #好像进库不需要知道来源
    msg = request.POST.get('msg')
    picfile = request.FILES.get('picfile')
    mymsg = json.loads(msg)
    picresult = mymsg.get('result')
    now_save = mymsg.get('save')
    car_type = mymsg.get('car_type')
    in_timer = datetime.datetime.now()
    if now_save == True:  # 放行存数据库
        # 存进库消息
        if car_type != 1:  # 不是月租车位，就去访客车位
            parking_type = 2
        else:
            parking_type = 1
        inpark_obj = EventLog.objects.create()
        Vobj = VirtualParking.objects.filter(apply=False, parkingtype=parking_type).first()
        if Vobj:
            # 车位锁定
            Vobj.apply = True
            Vobj.save()
            inpark_obj.virtualParking = Vobj
        inpark_obj.card_num = picresult
        inpark_obj.in_timer = in_timer  # 进库时间
        inpark_obj.in_pic = picfile
        inpark_obj.car_type = car_type
        inpark_obj.counteract = 0
        inpark_obj.save()
        # myid = inpark_obj.id
        # get_business_in(myid)  # 平台通讯
    else:  # 查找车类型的
        if car_type != 2:
            # user_obj = UserPaymentLog.objects.filter(user__car_number__iexact=picresult, end_time__gte=pictime)
            user_obj = UserProfile.objects.filter(car_number__iexact=picresult, expire_at__gte=in_timer)
            if user_obj:
                car_type = 1
            else:
                car_type = 3
    return HttpResponse(car_type)


@csrf_exempt
def vipin_parking(request):
    # origin_ip = request.META['REMOTE_ADDR']         #好像进库不需要知道来源
    msg = request.POST.get('msg')
    picfile = request.FILES.get('picfile')
    mymsg = json.loads(msg)
    picresult = mymsg.get('result')
    now_save = mymsg.get('save')
    in_timer = datetime.datetime.now()
    if now_save == True:  # 放行存数据库
        inpark_obj = VipEventLog.objects.create()
        inpark_obj.card_num = picresult
        inpark_obj.in_timer = in_timer  # 进库时间
        inpark_obj.in_pic = picfile
        inpark_obj.counteract = 0
        inpark_obj.save()

    return HttpResponse('OK')


@csrf_exempt
def vipout_parking(request):
    msg = request.POST.get('msg')
    filename = request.FILES.get('picfile')
    mymsg = json.loads(msg)
    # print(mymsg)
    picresult = mymsg.get('result')
    expiry_date = 0
    in_time = timer = datetime.datetime.now()
    TimeLength = 1800
    in_pic = None
    obj = VipEventLog.objects.filter(card_num=picresult, counteract=0).order_by('-in_timer').first()
    # print(obj)
    if obj:  # 最正常的找到进库信息
        in_time = datetime.datetime.strftime(obj.in_timer, '%Y-%m-%d %H:%M:%S')
        if obj.in_pic:
            in_pic = obj.in_pic.url
        else:
            in_pic = ''
        # 存出库消息
        obj.out_timer = timer
        obj.out_pic = filename
        obj.counteract = 1  # 出入抵消了
        TimeLength = int((timer - obj.in_timer).seconds)
        obj.save()
        VipEventLog.objects.filter(card_num=picresult).update(counteract=1)  # 所有进库消息更新为抵消了
    else:  # 未找到进库消息，先查找是否月租用户，
        obj = VipEventLog.objects.create()
        # 存出库消息
        obj.card_num = picresult
        obj.out_timer = timer
        obj.out_pic = filename
        obj.counteract = 1  # 出入抵消了
        obj.save()
    # 找包月车的到期日
    user_obj = UserProfile.objects.filter(car_number__iexact=picresult, vip=True, expire_at__gte=timer).first()
    if user_obj:
        expiry_date = user_obj.expire_at
        nowtime = datetime.datetime.now()
        expiry_date = (expiry_date - nowtime).days
    else:
        obj.avtomatik = False
        obj.car_type = 3
        obj.save()
    # 返回入库信息
    return JsonResponse({'TimeLength': TimeLength, 'inpark_time': in_time, 'in_pic': in_pic, 'expiry': expiry_date})


@csrf_exempt
def out_parking_list(request):
    msg = request.POST.get('msg')
    filename = request.FILES.get('picfile')
    mymsg = json.loads(msg)
    car_type = mymsg.get('car_type')
    # print(mymsg)
    picresult = mymsg.get('result')
    errorout = mymsg.get('errorout')
    expiry_date = 0
    timer = datetime.datetime.now()
    # print(type(picresult) , picresult)
    if errorout == '无法进库记录匹配':
        obj = EventLog.objects.create()
        # 存出库消息
        obj.card_num = picresult
        obj.out_timer = timer
        obj.car_type = 3  # 1、月租 2、特殊 3、临时卡
        obj.out_pic = filename
        obj.counteract = 1  # 出入抵消了
        obj.save()
        myid = obj.id
        return JsonResponse({'car_type': 11, 'myid': myid})  # 没有找到匹配的进入信息
    if picresult == '':  # 这种情况应该是不存在的
        return JsonResponse({'car_type': 11})  # 没有找到匹配的进入信息

    virtual = EventLog.objects.filter(card_num=picresult, virtualParking__apply=True)  # 有车位的放释放
    for item in virtual:
        item.virtualParking.apply = False
        item.virtualParking.save()

    obj = EventLog.objects.filter(card_num=picresult, counteract=0).order_by('-in_timer').first()
    # print(obj)
    if obj:  # 最正常的找到进库信息，
        car_type = obj.car_type
        in_time = datetime.datetime.strftime(obj.in_timer, '%Y-%m-%d %H:%M:%S')
        if obj.in_pic:
            in_pic = obj.in_pic.url
        else:
            in_pic = ''
        myid = obj.id
        # 存出库消息
        obj.out_timer = timer
        obj.out_pic = filename
        obj.counteract = 1  # 出入抵消了
        TimeLength = int((timer - obj.in_timer).seconds)
        obj.save()
        myid = obj.id
        # if car_type == 1 or car_type == 2:
        # get_business_out(myid)  # 月卡车辆直接上传平台，出库消息
        EventLog.objects.filter(card_num=picresult).update(counteract=1)  # 所有进库消息更新为抵消了

    else:  # 未找到进库消息，先查找是否月租用户，
        user_obj = UserProfile.objects.filter(car_number__iexact=picresult, expire_at__gte=timer).first()
        if user_obj or car_type == 2:
            if user_obj:
                car_type = 1
                end_time = user_obj.expire_at
            else:
                end_time = timer + datetime.timedelta(days=1)  # 这里是特殊车辆，有效期加 1天
            obj = EventLog.objects.create()
            # 存出库消息
            obj.card_num = picresult
            obj.car_type = car_type  # 1、月租 2、特殊
            obj.out_timer = timer
            obj.out_pic = filename
            obj.counteract = 1  # 出入抵消了
            obj.save()
            myid = obj.id
            expiry_date = (end_time - timer).days
            return JsonResponse({'car_type': car_type, 'TimeLength': 0, 'inpark_time': '', 'in_pic': '', 'myid': myid,
                                 'expiry': expiry_date})
        else:
            return JsonResponse({'car_type': 11, 'TimeLength': 0, 'inpark_time': '', 'in_pic': 'error', 'myid': '',
                                 'expiry': ''})  # 没有找到匹配的进入信息
    # 找包月车的到期日
    # user_obj = UserPaymentLog.objects.filter(user__car_number__iexact=picresult, end_time__gte=pictime).first()

    user_obj = UserProfile.objects.filter(car_number__iexact=picresult, expire_at__gte=timer).first()
    if user_obj:
        expiry_date = user_obj.expire_at
        nowtime = datetime.datetime.now()
        expiry_date = (expiry_date - nowtime).days
        # print('------------days:', day_lost)
    # 返回入库信息
    return JsonResponse(
        {'car_type': car_type, 'TimeLength': TimeLength, 'inpark_time': in_time, 'in_pic': in_pic, 'myid': myid,
         'expiry': expiry_date})


@csrf_exempt
def result_error_list(request):
    # 所有没抓到的车牌，或者识别抓错了的车牌都放在这里了。
    maybe_num = request.POST.get('car_num')
    find_type = int(request.POST.get('find_type'))
    data_list = []
    print(find_type, type(find_type))
    if find_type == 1:
        obj1 = EventLog.objects.filter(card_num__contains=maybe_num, in_pic__startswith='upload/', counteract=0)
    elif find_type == 2:
        obj1 = EventLog.objects.filter(card_num='', in_pic__startswith='upload/', counteract=0)
    else:
        obj1 = EventLog.objects.filter(in_pic__startswith='upload/', counteract=0)
    # print(obj1)
    for item in obj1:
        pic_msg = {}
        pic_msg['pic'] = item.in_pic.url
        pic_msg['id'] = str(item.id)
        data_list.append(pic_msg)
    print(data_list)
    return HttpResponse(json.dumps(data_list))


@csrf_exempt
def payment_spot(request):
    msg = request.POST.get('msg')
    mymsg = json.loads(msg)
    # print(mymsg)
    myid = int(mymsg.get('myid'))
    payable = mymsg.get('payable')
    actuallypay = mymsg.get('actuallypay')
    if myid < 0:
        obj = EventLog.objects.create()
        obj.payMoney = actuallypay
        obj.factMoney = payable
        obj.save()
        # 付费车辆上传平台
        # getid = obj.id
        # get_business_out(getid)
        return HttpResponse('payment ok')

    obj = EventLog.objects.get(id=myid)
    if obj:
        obj.payMoney = actuallypay
        obj.factMoney = payable
        obj.save()
        # 付费车辆上传平台
        # getid = obj.id
        # get_business_out(getid)
    return HttpResponse('payment ok')


@csrf_exempt
def makit(request):
    msg = request.POST.get('msg')
    filename = request.FILES.get('picfile')
    mymsg = json.loads(msg)
    # print(mymsg)
    picresult = mymsg.get('result')
    myid = mymsg.get('id')
    expiry_date = 0
    TimeLength = 30
    timer = datetime.datetime.now()
    obj = EventLog.objects.get(id=int(myid))
    # print(obj)
    in_time = datetime.datetime.strftime(obj.in_timer, '%Y-%m-%d %H:%M:%S')
    car_type = obj.car_type
    in_pic = obj.in_pic.url
    old_picresult = obj.card_num
    # print('old_picresult', old_picresult)
    # 存出库消息
    if '手动' in str(old_picresult) and '手动' not in str(picresult):
        obj.card_num = picresult
        car_num = picresult
    else:
        obj.card_num = old_picresult
        car_num = old_picresult
    obj.out_timer = timer
    obj.out_pic = filename
    obj.counteract = 1  # 出入抵消了
    if obj.virtualParking:
        obj.virtualParking.apply = False
        obj.virtualParking.save()
    obj.save()
    TimeLength = int((timer - obj.in_timer).seconds)  # 停车时长
    print('car_num', car_num)
    if car_type == 1:
        # user_obj = UserPaymentLog.objects.filter(user__car_number__iexact=car_num, end_time__gte=pictime).first()
        user_obj = UserProfile.objects.filter(car_number__iexact=car_num, expire_at__gte=timer).first()
        if user_obj:
            end_time = user_obj.expire_at
            expiry_date = (end_time - timer).days

    # 返回入库信息
    return JsonResponse(
        {'car_type': car_type, 'in_pic': in_pic, 'car_num': car_num, 'inpark_time': in_time, 'myid': myid,
         'expiry': expiry_date, 'TimeLength': TimeLength})


@csrf_exempt
def qtstart_msg(request):  # PYQT开机时显示记录
    in_data = []
    out_data = []
    parking_name = ''
    parking_add = ''
    totBerthNum = ''
    free_time = 0
    max_day = 80
    one_eight = 10
    work_time_st = '00:00:00'
    work_time_ed = '23:59:59'

    in_obj = EventLog.objects.filter(~Q(in_timer=None)).order_by('-in_timer')[:2]
    for item in in_obj:
        in_row = {}
        in_row['car_num'] = item.card_num
        in_row['in_timer'] = datetime.datetime.strftime(item.in_timer, '%Y-%m-%d %H:%M:%S')
        in_row['car_type'] = item.car_type
        in_data.append(in_row)

    out_obj = EventLog.objects.filter(~Q(out_timer=None)).order_by('-out_timer')[:2]
    for item in out_obj:
        out_timer = item.out_timer
        out_row = {}
        out_row['car_num'] = item.card_num
        in_timer = item.in_timer
        if in_timer:
            out_row['in_timer'] = datetime.datetime.strftime(item.in_timer, '%Y-%m-%d %H:%M:%S')
        else:
            out_row['in_timer'] = '未知'
        out_row['out_timer'] = datetime.datetime.strftime(out_timer, '%Y-%m-%d %H:%M:%S')
        out_row['car_type'] = item.car_type
        out_row['dueMoney'] = item.dueMoney  # 应该收
        out_row['payMoney'] = item.payMoney  # 实收
        out_data.append(out_row)
    # 基础信息
    parkingmsg_obj = ParkingLot.objects.all().first()  # 取ID号最小的那条记录
    if parkingmsg_obj:
        parking_name = parkingmsg_obj.parking_name
        parking_add = parkingmsg_obj.parking_add
        totBerthNum = parkingmsg_obj.totBerthNum
        work_time_st = str(parkingmsg_obj.work_time_st)
        work_time_ed = str(parkingmsg_obj.work_time_ed)
    # 动态车位信息
    monthlyRemainNum = VirtualParking.objects.filter(apply=0, parkingtype=1).count()  # 月租剩余车位
    guestRemainNum = VirtualParking.objects.filter(apply=0, parkingtype=2).count()  # 访客剩余车位

    # 计费基础
    expense_obj = Expense.objects.all().first()
    if expense_obj:
        free_time = expense_obj.free_time  # 以分钟为单位
        max_day = expense_obj.max_day  # 最大限额
        one_eight = expense_obj.basic  # 暂时为起步价

    return JsonResponse({'in': in_data, 'out': out_data, 'parking_name': parking_name, 'totBerthNum': totBerthNum,
                         'parking_add': parking_add, 'monthlyRemainNum': monthlyRemainNum,
                         'guestRemainNum': guestRemainNum, 'work_time_st': work_time_st, 'work_time_ed': work_time_ed,
                         'free_time': free_time, 'max_day': max_day, 'one_eight': one_eight})


@csrf_exempt
def berth_msg(request):  # 取得动态停车场泊位
    totRemainNum = VirtualParking.objects.filter(apply=0).count()  # 总剩余车位
    monthlyRemainNum = VirtualParking.objects.filter(apply=0, parkingtype=1).count()  # 月租剩余车位
    guestRemainNum = VirtualParking.objects.filter(apply=0, parkingtype=2).count()  # 访客剩余车位

    return JsonResponse(
        {'monthlyRemainNum': monthlyRemainNum, 'guestRemainNum': guestRemainNum, 'totRemainNum': totRemainNum})


@csrf_exempt
def index(request):
    """
    管理端首页
    :param request:
    :return:
    """
    context = {}
    return render(request, 'index.html', context=context)


@csrf_exempt
def page_not_found(request):
    context = {}
    return render(request, 'error404.html', context=context)


def login(request):
    """
    登录
    :param request:
    :return:
    """
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('pwd')
        user = auth.authenticate(username=username, password=password)
        if user:
            auth.login(request, user)
            go_to = '/'
            next = request.GET.get('next', None)
            if next:
                go_to = next
            return HttpResponseRedirect(go_to)
        else:
            return render(request, 'login.html',
                          {'error': "用户名或密码输入错误.", 'username': username, 'pwd': password})
    else:
        return render(request, 'login.html')


def logout(request):
    """
    logout
    :param request:
    :param arg:
    :return:
    """
    auth.logout(request)
    context = {}
    return render(request, 'index.html', context=context)
    # return HttpResponseRedirect('/login')


@login_required()
# @common_tools.permission_required
def report(request, id):
    """
    报表
    :param request:
    :return:
    """
    context = {}
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    # print(start_time, end_time, '======')
    if not start_time:
        start_time = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
    if not end_time:
        end_time = datetime.datetime.now().strftime('%Y-%m-%d')
    context['start_time'] = start_time
    context['end_time'] = end_time
    if id == '1':
        return render(request, 'manager/report_income.html', context)
    else:
        return render(request, 'manager/report_flow.html', context)


@login_required()
def report_income(request):
    """
    车场收入
    :param request:
    :return:
    """
    context = {}
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    if not start_time:
        start_time = datetime.datetime.now() - datetime.timedelta(days=7)
    if not end_time:
        end_time = datetime.datetime.now()
    date = datetime.datetime.now()
    start_time = datetime.datetime.strptime('%s %s:%s:%s' % (start_time, date.hour, date.minute, date.second),
                                            '%Y-%m-%d %H:%M:%S')
    end_time = datetime.datetime.strptime('%s %s:%s:%s' % (end_time, date.hour, date.minute, date.second),
                                          '%Y-%m-%d %H:%M:%S')
    day_list = common_tools.get_days(start_time, end_time)
    select = {'day': connection.ops.date_trunc_sql('day', 'update_at')}
    event_logs = EventLog.objects \
        .filter(update_at__gte=start_time, update_at__lt=end_time, counteract=1) \
        .extra(select=select) \
        .values('day').annotate(income=Sum('payMoney')) \
        .order_by('day')
    income_dict = {}
    parking_list = []
    series_list = []
    for event in event_logs:
        # print('event:',event,'#############')
        income_dict[event['day'].strftime('%Y-%m-%d')] = event['income']
    tmp = {
        'name': '车场收入',
        'type': 'line',
        'data': []
    }
    for day in day_list:
        tmp['data'].append(income_dict.get(day, 0) or 0)
    series_list.append(tmp)
    context['day_list'] = day_list
    context['series_list'] = series_list
    context['parking_list'] = parking_list
    return HttpResponse(json.dumps(context))


@login_required()
def report_flow(request):
    """
    车场流量
    :param request:
    :return:
    """
    context = {}
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    # print(start_time, end_time, '----------')
    if not start_time:
        start_time = datetime.datetime.now() - datetime.timedelta(days=7)
    if not end_time:
        end_time = datetime.datetime.now()
    date = datetime.datetime.now()
    start_time = datetime.datetime.strptime('%s %s:%s:%s' % (start_time, date.hour, date.minute, date.second),
                                            '%Y-%m-%d %H:%M:%S')
    end_time = datetime.datetime.strptime('%s %s:%s:%s' % (end_time, date.hour, date.minute, date.second),
                                          '%Y-%m-%d %H:%M:%S')
    day_list = common_tools.get_days(start_time, end_time)
    select = {'day': connection.ops.date_trunc_sql('day', 'update_at')}
    event_logs = EventLog.objects \
        .filter(update_at__gte=start_time, update_at__lt=end_time) \
        .extra(select=select) \
        .values('day').annotate(flow=Count('id')) \
        .order_by('day')
    flow_dict = {}
    parking_list = []
    series_list = []
    for event in event_logs:
        flow_dict[event['day'].strftime('%Y-%m-%d')] = event['flow']  # mysql数据库，永远搞不清楚日期时间怎么格式化，要不要格式化
    tmp = {
        'name': '车场进出流量',
        'type': 'line',
        'data': []
    }
    for day in day_list:
        tmp['data'].append(flow_dict.get(day, 0) or 0)
    series_list.append(tmp)
    context['day_list'] = day_list
    context['series_list'] = series_list
    context['parking_list'] = parking_list
    return HttpResponse(json.dumps(context))


@login_required()
def export_flow(request):
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    select = {'day': connection.ops.date_trunc_sql('day', 'update_at')}
    event_logs = EventLog.objects \
        .filter(update_at__gte=start_time, update_at__lt=end_time) \
        .extra(select=select) \
        .values('day').annotate(flow=Count('id')) \
        .order_by('day')
    export_data = []
    for row in event_logs:
        export_data.append([row['day'].strftime('%Y-%m-%d'), row['flow']])
        # print('--->>', row)
    return render_to_excel(['日期', '流量'], export_data, 'flow.xls', title='车场流量一览')


@login_required()
def export_income(request):
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    select = {'day': connection.ops.date_trunc_sql('day', 'update_at')}
    event_logs = EventLog.objects \
        .filter(update_at__gte=start_time, update_at__lt=end_time, counteract=1) \
        .extra(select=select) \
        .values('day').annotate(income=Sum('payMoney')) \
        .order_by('day')
    export_data = []
    for row in event_logs:
        export_data.append([row['day'].strftime('%Y-%m-%d'), row['income']])
    return render_to_excel(['日期', '收入'], export_data, 'income.xls', title='车场收入一览')


@csrf_exempt
def events(request):
    """
    事件列表
    :param request:
    :return:
    """
    context = {}
    now = datetime.datetime.now()
    start = now - datetime.timedelta(hours=71, minutes=59, seconds=59)
    events_list = EventLog.objects.filter(Q(in_timer__gt=start) | Q(out_timer__gt=start)).order_by('-id')
    context['events_list'] = events_list
    return render(request, 'manager/events_list.html', context)


@csrf_exempt
def vipevents(request):
    """
    VIP车库事件列表
    :param request:
    :return:
    """
    context = {}
    now = datetime.datetime.now()
    start = now - datetime.timedelta(hours=71, minutes=59, seconds=59)
    events_list = VipEventLog.objects.filter(Q(in_timer__gt=start) | Q(out_timer__gt=start)).order_by('-id')
    context['vipevents_list'] = events_list
    return render(request, 'manager/vipevents_list.html', context)


@login_required()
def export_events(request):
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    event_logs = EventLog.objects.filter(create_at__gte=start_time, create_at__lt=end_time)
    export_data = []
    # (1, '月租'), (3, '临时车'), (2, '特殊车辆')
    car_type_dict = {1: '月租',
                     2: '特殊车辆',
                     3: '临时车'}
    for row in event_logs:
        if row.in_timer:
            intimer = row.in_timer.strftime('%Y-%m-%d %H:%M:%S')
        else:
            intimer = ''
        if row.out_timer:
            outtimer = row.out_timer.strftime('%Y-%m-%d %H:%M:%S')
        else:
            outtimer = ''
        export_data.append([row.card_num,
                            car_type_dict.get(row.car_type),
                            intimer,
                            outtimer,
                            row.factMoney,
                            row.payDiscount,
                            row.payMoney
                            ])
    # return HttpResponse(export_data)
    return render_to_excel(['车牌', '车辆类型', '进库时间', '出库时间', '计费金额', '折扣金额', '实付金额'],
                           export_data, 'events.xls', title='历史业务明细表')


@login_required()
def export_vipevents(request):
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    event_logs = VipEventLog.objects.filter(create_at__gte=start_time, create_at__lt=end_time)
    export_data = []

    for row in event_logs:
        if row.in_timer:
            intimer = row.in_timer.strftime('%Y-%m-%d %H:%M:%S')
        else:
            intimer = ''
        if row.out_timer:
            outtimer = row.out_timer.strftime('%Y-%m-%d %H:%M:%S')
        else:
            outtimer = ''
        export_data.append([row.card_num,
                            intimer,
                            outtimer,
                            ])
    # return HttpResponse(export_data)
    return render_to_excel(['车牌', '进库时间', '出库时间'],
                           export_data, 'events.xls', title='VIP车库历史业务明细表')


@login_required()
def histroy_list(request):
    """
    历史明细
    :param request:
    :return:
    """
    context = {}
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    if not start_time:
        start_time = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
    if not end_time:
        end_time = datetime.datetime.now().strftime('%Y-%m-%d')

    events_list = EventLog.objects.filter(
        Q(in_timer__gte=start_time) | Q(out_timer__gte=end_time) | Q(in_timer__gte=end_time) | Q(
            out_timer__gte=start_time)).order_by('-id')
    # events_list = EventLog.objects.all()
    context['start_time'] = start_time
    context['end_time'] = end_time
    context['events_histroy'] = events_list
    return render(request, 'manager/histroy_list.html', context)


@login_required()
def viphistroy_list(request):
    """
    VIP车库历史明细
    :param request:
    :return:
    """
    context = {}
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    if not start_time:
        start_time = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
    if not end_time:
        end_time = datetime.datetime.now().strftime('%Y-%m-%d')

    events_list = VipEventLog.objects.filter(
        Q(in_timer__gte=start_time) | Q(out_timer__gte=end_time) | Q(in_timer__gte=end_time) | Q(
            out_timer__gte=start_time)).order_by('-id')
    # events_list = EventLog.objects.all()
    context['start_time'] = start_time
    context['end_time'] = end_time
    context['events_viphistroy'] = events_list
    return render(request, 'manager/viphistroy_list.html', context)


# 自动添加泊位编号
@csrf_exempt
def auto_parkingnum(request):
    # 先删除里面的记录
    VirtualParking.objects.all().delete()
    parkinglot_obj = ParkingLot.objects.all().first()  # 取ID号最小的那条记录
    monthlyBerthNum = parkinglot_obj.monthlyBerthNum  # 月租车位
    guesBerthNum = parkinglot_obj.guesBerthNum  # 临时车位

    for i in range(1, monthlyBerthNum + 1):
        obj = VirtualParking.objects.create()
        obj.parkingnum = 'P' + str(i)
        obj.parkingtype = 1
        obj.save()

    for i in range(1, guesBerthNum + 1):
        obj = VirtualParking.objects.create()
        obj.parkingnum = 'T' + str(i)
        obj.parkingtype = 2
        obj.save()
    month_Num = VirtualParking.objects.filter(parkingtype=1).count()
    gues_Num = VirtualParking.objects.filter(parkingtype=2).count()
    all_num = VirtualParking.objects.count()

    retxt = '泊位自动编号成功！\n' + '总车位： ' + str(all_num) + '\n月租车位： ' + str(month_Num) + '\n访客车位： ' + str(gues_Num)

    return HttpResponse(retxt)
